#!/usr/bin/perl
use File::Copy;

# version $Id: view.cgi 25 2009-12-12 21:56:04Z olivier.courtade@gmail.com $

$js="";

print "Content-type: text/html\n\n";

# Are we authenticated yet ?

if (open (IN,"/usr/syno/synoman/webman/modules/authenticate.cgi|")) {
	$user=<IN>;
	chop($user);
	close(IN);
}


# if not admin or no user at all...no authentication...so, bye-bye

if ($user ne 'admin') {
	print "<HTML><HEAD><TITLE>Login Required</TITLE></HEAD><BODY>Please login as admin first, before using this webpage</BODY></HTML>\n";
	die;
}


# get configuration status
# and language settings
if (open(IN,"/etc/synoinfo.conf")) {
	while (<IN>) {
		($key,$value)=/([^=]+)="([^"]+)"/;
		if ($key eq 'language') {
			# needed to get translation table
			if ($value ne 'def') {
				$lang=$value;
			} else {
				$_=$ENV{'HTTP_ACCEPT_LANGUAGE'};
				($lang)=/^([^,;]+)/;
			}
		} 
	}
	close(IN);
}

$js .= "<!-- info: language set to \"".$lang."\" -->\n";

# load translations
$path=$0;
$path=~ s#/[^/]*$##;

$js .= "<!-- info: path set to \"".$path."\" -->\n";


my $langfile=$path ."/lang/" .$lang;
my %translation;

if (open(IN,$langfile)) {
	while(<IN>) {
		if (!(/^#/)) {
			($key,$value)=/"([^"]+)"\s*,\s*"([^"]+)"/;
			$translation{$key}=$value;
		}
	}
	close(IN);
} else {
    $erreur = $!;
    $js .= "<!-- info: unable to open ".$langfile."  due to ".$erreur."-->\n";
}

# translation subroutine
sub trans {
	local ($tt,$ret);
	$tt=@_[0];
	if ($translation{$tt}) {
		$ret=$translation{$tt};
	} else {
		$ret=$tt;
	}
	return $ret;
}


sub addCfgFile {
	($fname,$name)=@_;
	$fname=~s/^\s*//g;
	$name=~s/^\s*//g;
	if ($tmpljs{'names'}) {
		$tmpljs{'names'}.=',';
	}
	$tmpljs{'names'}.="'" .$name ."'" ;
}

$gotown=0;
if (open(IN,"configfiles.txt")) {
	while(<IN>) {
		chop();
		if ((!(/^#/))&&(/,/)) {
			($fname,$name)=/([^,]+),(.*)/;
			addCfgFile($fname,$name);
		}
	}
}

# get javascript

$js .= 'var ttchooseconfigfile="'.trans("Choose config file").'";' ."\n";
$js .= 'var ttbackbutton="'.trans("Back").'";' ."\n";
$js .= 'var viewbutton="'.trans("View files and logs").'";' ."\n";

if (open(IN,"script.js")) {
	while (<IN>) {
		s/==:([^:]+):==/$tmpljs{$1}/g;
		$js.=$_;
	}
	close(IN);
}


$tmplhtml{'javascript'}=$js;
$tmplhtml{'debug'}=$debug;
$tmplhtml{'BACK'}=trans("Back");
# print html page
if (open(IN,"page.html")) {
	while (<IN>) {
		s/==:([^:]+):==/$tmplhtml{$1}/g;
		print $_;
	}
	close(IN);
}
